<template>
  <div class="order-container">
    <!-- 左侧菜单 -->
    <div class="left-menu">
      <div class="menu-section">
        <h3>订单中心</h3>
        <ul>
          <li class="active">我的订单</li>
          <li>评价晒单</li>
          <li>话费充值订单</li>
          <li>以旧换新订单</li>
        </ul>
      </div>

      <div class="menu-section">
        <h3>个人中心</h3>
        <ul>
          <li><a href="#/portal">我的个人中心</a></li>
          <li>消息通知</li>
          <li>购买资格</li>
          <li>现金账户</li>
          <li>小米礼品卡</li>
          <li>现金券</li>
          <li>喜欢的商品</li>
          <li>优惠券</li>
          <li>收益地址</li>
          <li>红包</li>
        </ul>
      </div>

      <div class="menu-section">
        <h3>售后服务</h3>
        <ul>
          <li>服务记录</li>
          <li>申请服务</li>
          <li>领取快递报销</li>
        </ul>
      </div>
      <div class="menu-section">
        <h3>账户管理</h3>
        <ul>
          <li><a href="#/zhanghao">个人信息</a></li>
          <li><a href="#/zhanghao">修改密码</a></li>
          <li>注销服务</li>
        </ul>
      </div>
    </div>

    <!-- 右侧内容 -->
    <div class="right-content">
      <div class="content-header">
        <div class="breadcrumb">
          <span>首页</span>
          <span class="divider">/</span>
          <span>交易订单</span>
        </div>
        <h2>我的订单</h2>
        <p class="subtitle">请填写你的最新订单信息，了解更多></p>

        <div class="order-tabs">
          <div class="tab active">全部有效订单</div>
          <div class="tab">待支付</div>
          <div class="tab">待收货</div>
          <div class="tab">订单回收站</div>
        </div>

        <div class="search-bar">
          <input type="text" placeholder="输入商品名称、订单号">
          <button class="search-btn">搜索</button>
        </div>
      </div>

      <div class="order-list">
        <div v-for="order in orderList" :key="order.orderid" class="order-item">
          <div class="order-header">
            <span class="order-date">下单时间：{{ formatDisplayTime(order.ftime) }}</span>
            <span class="arrival-time">{{ getArrivalTimeText(order) }}</span>
            <span class="order-number">订单号：{{ order.ordernum }}</span>
            <span class="order-payment">微信支付APP</span>
            <span class="order-status" :class="getStatusClass(order)">{{ getOrderStatus(order) }}</span>
          </div>

          <div class="order-body" v-for="goods in order.details" :key="goods.gid">
            <div class="goods-info">
              <div class="goods-item">
                <img :src="`../../public/images/${goods.img}`" :alt="goods.gname" class="goods-image">
                <div class="goods-detail">
                  <div class="goods-name">{{ goods.gname }}</div>
                  <div class="goods-spec">黑色 改装快照</div>
                  <div class="goods-price">¥{{ goods.price }} x {{ goods.num }}</div>
                </div>
              </div>
            </div>

            <div class="order-total">
              <div class="total-amount">¥{{ order.total }}</div>
              <div class="total-text">支付金额</div>
            </div>

            <div class="order-actions">
              <button class="action-btn">订单详情</button>
              <button class="action-btn"><router-link :to="`/shaidan?gid=${ goods.gid }`">评价晒单</router-link></button>
              <button class="action-btn">申请售后</button>
              <button class="action-btn">联系客服</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import axios from '../api/axios'
import { ref } from 'vue'
import { useRouter } from 'vue-router'
const router = useRouter()

const orderList = ref([]) // 订单列表数据

// 格式化显示时间（年月日 时分）
const formatDisplayTime = (timeStr) => {
  if (!timeStr) return ''
  const date = new Date(timeStr.replace(/-/g, '/'))
  return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日 ${date.getHours()}:${date.getMinutes().toString().padStart(2, '0')}`
}

// 将时间字符串转换为Date对象
const parseTime = (timeStr) => {
  if (!timeStr) return null
  return new Date(timeStr.replace(/-/g, '/'))
}

// 计算小时差
const getHoursDiff = (startTime, endTime) => {
  const diff = endTime.getTime() - startTime.getTime()
  return diff / (1000 * 60 * 60) // 转换为小时
}

// 获取订单状态
const getOrderStatus = (order) => {
  const now = new Date()
  const createTime = parseTime(order.ftime)
  const arrivalTime = parseTime(order.fatime)

  // 已取消订单优先显示
  if (order.state === 3) return '已取消'

  // 已到达收货时间
  if (arrivalTime && now >= arrivalTime) return '已收货'

  // 计算下单后经过的小时数
  if (createTime) {
    const hoursPassed = getHoursDiff(createTime, now)

    // 下单超过2小时
    if (hoursPassed >= 2) return '发货中'

    // 下单不足2小时
    return '待发货'
  }

  // 默认状态
  return '待处理'
}

// 获取到货时间显示文本
const getArrivalTimeText = (order) => {
  const status = getOrderStatus(order);
  const createTime = parseTime(order.ftime);
  const arrivalTime = parseTime(order.fatime);

  if (status === '已收货' && arrivalTime) {
    return `到货时间：${formatDisplayTime(order.fatime)}`;
  }

  if (createTime && arrivalTime) {
    const days = Math.ceil((arrivalTime - createTime) / (1000 * 60 * 60 * 24));
    return `预计${days}天后到达`;
  }

  return '';
}

// 获取状态对应的CSS类
const getStatusClass = (order) => {
  const status = getOrderStatus(order)
  return {
    'cancelled': status === '已取消',
    'pending': status === '待发货',
    'delivering': status === '发货中',
    'received': status === '已收货',
    'processing': status === '待处理'
  }
}

if (sessionStorage.getItem('user')) {
  let userid = JSON.parse(sessionStorage.getItem('user')).userid
  // 获取订单数据
  axios.post('/api/orders/ordersByU', { userid }).then((res) => {
    if (res.data.code == 200) {
      orderList.value = res.data.orders
      console.log('订单数据:', orderList.value)
    } else {
      alert(res.data.msg)
    }
  })
} else {
  alert('请先登录')
  router.push('/login')
}
</script>

<style lang="scss" scoped>
.order-container {
  display: flex;
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px 0;
  background-color: #f5f5f5;

  .left-menu {
    width: 200px;
    margin-right: 20px;
    background: white;
    border-radius: 8px;
    padding: 15px 0;

    .menu-section {
      margin-bottom: 20px;

      h3 {
        font-size: 16px;
        color: #333;
        padding: 0 20px;
        margin-bottom: 10px;
      }

      ul {
        list-style: none;
        padding: 0;
        margin: 0;

        li {
          padding: 10px 20px;
          cursor: pointer;
          font-size: 14px;
          color: #666;

          &:hover {
            color: #ff6700;
            background-color: #f5f5f5;
          }

          &.active {
            color: #ff6700;
            background-color: #f5f5f5;
            border-left: 2px solid #ff6700;
          }
        }

        a {
          color: inherit; /* 确保链接颜色继承父元素的颜色 */
          text-decoration: none;

          &:hover {
            color: #ff6700;
          }
        }
      }
    }
  }

  .right-content {
    flex: 1;
    background: white;
    border-radius: 8px;
    padding: 20px;

    .content-header {
      margin-bottom: 20px;

      .breadcrumb {
        font-size: 12px;
        color: #999;
        margin-bottom: 15px;

        .divider {
          margin: 0 5px;
        }
      }

      h2 {
        font-size: 24px;
        color: #333;
        margin-bottom: 5px;
      }

      .subtitle {
        font-size: 14px;
        color: #999;
        margin-bottom: 20px;
      }

      .order-tabs {
        display: flex;
        border-bottom: 1px solid #eee;
        margin-bottom: 20px;

        .tab {
          padding: 10px 20px;
          font-size: 14px;
          color: #666;
          cursor: pointer;

          &:hover {
            color: #ff6700;
          }

          &.active {
            color: #ff6700;
            border-bottom: 2px solid #ff6700;
          }
        }
      }

      .search-bar {
        display: flex;
        margin-bottom: 20px;

        input {
          flex: 1;
          height: 36px;
          padding: 0 10px;
          border: 1px solid #e0e0e0;
          border-radius: 4px 0 0 4px;
          outline: none;

          &:focus {
            border-color: #ff6700;
          }
        }

        .search-btn {
          width: 80px;
          height: 36px;
          background-color: #ff6700;
          color: white;
          border: none;
          border-radius: 0 4px 4px 0;
          cursor: pointer;

          &:hover {
            background-color: #f25807;
          }
        }
      }
    }

    .order-list {
      .order-item {
        border: 1px solid #e0e0e0;
        border-radius: 8px;
        margin-bottom: 20px;
        overflow: hidden;

        .order-header {
          .order-status {
            &.pending {
              color: #E6A23C;
              /* 待发货 - 橙色 */
            }

            &.delivering {
              color: #409EFF;
              /* 发货中 - 蓝色 */
            }

            &.received {
              color: #67C23A;
              /* 已收货 - 绿色 */
            }

            &.cancelled {
              color: #909399;
              /* 已取消 - 灰色 */
            }

            &.processing {
              color: #F56C6C;
              /* 待处理 - 红色 */
            }
          }
        }

        .order-body {
          display: flex;
          padding: 20px;

          .goods-info {
            display: flex;
            flex: 1;

            .goods-image {
              width: 80px;
              height: 80px;
              margin-right: 20px;
              border: 1px solid #f0f0f0;
            }

            .goods-detail {
              .goods-name {
                font-size: 16px;
                color: #333;
                margin-bottom: 5px;
              }

              .goods-spec {
                font-size: 14px;
                color: #999;
                margin-bottom: 5px;
              }

              .goods-price {
                font-size: 14px;
                color: #333;
              }
            }
          }

          .order-total {
            width: 150px;
            text-align: right;
            padding-right: 20px;

            .total-amount {
              font-size: 18px;
              color: #ff6700;
              margin-bottom: 5px;
            }

            .total-text {
              font-size: 12px;
              color: #999;
            }
          }

          .order-actions {
            width: 200px;
            display: flex;
            flex-direction: column;
            align-items: flex-end;

            .action-btn {
              width: 80px;
              height: 30px;
              margin-bottom: 10px;
              background: white;
              border: 1px solid #e0e0e0;
              border-radius: 4px;
              color: #666;
              cursor: pointer;

              &:hover {
                color: #ff6700;
                border-color: #ff6700;
              }

              &:last-child {
                margin-bottom: 0;
              }
            }
          }
        }
      }
    }
  }
}

.arrival-time {
  margin-right: 15px;
  color: #666;
  font-size: 14px;
}

.order-header {
  display: flex;
  align-items: center;
  padding: 12px 20px;
  background-color: #fafafa;
  border-bottom: 1px solid #e0e0e0;
  font-size: 14px;

  >span {
    margin-right: 20px;
    white-space: nowrap;

    &:last-child {
      margin-right: 0;
    }
  }

  .order-date {
    color: #333;
    min-width: 180px;
  }

  .arrival-time {
    color: #666;
    min-width: 120px;
  }

  .order-number {
    color: #999;
    flex: 1;
    min-width: 200px;
  }

  .order-payment {
    color: #999;
    min-width: 100px;
  }

  .order-status {
    font-weight: 500;
    min-width: 80px;
    text-align: right;

    &.pending {
      color: #E6A23C;
      /* 待发货 - 橙色 */
    }

    &.delivering {
      color: #409EFF;
      /* 发货中 - 蓝色 */
    }

    &.received {
      color: #67C23A;
      /* 已收货 - 绿色 */
    }

    &.cancelled {
      color: #909399;
      /* 已取消 - 灰色 */
    }
  }
}

.goods-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;

  &:last-child {
    margin-bottom: 0;
  }

  .goods-image {
    width: 80px;
    height: 80px;
    margin-right: 20px;
    border: 1px solid #f0f0f0;
  }

  .goods-detail {
    .goods-name {
      font-size: 16px;
      color: #333;
      margin-bottom: 5px;
    }

    .goods-spec {
      font-size: 14px;
      color: #999;
      margin-bottom: 5px;
    }

    .goods-price {
      font-size: 14px;
      color: #333;
    }
  }
}
</style>
